<template>
  <view>
    <view v-if="hasData">
      <view class="cu-bar bg-white search fixed" :style="[{top:CustomBar + 'px'}]">
        <view class="search-form round">
          <text class="cuIcon-search"></text>
          <input type="text" placeholder="输入搜索的关键词" confirm-type="search" @input="onSearchInput"/>
        </view>
        <!-- <view class="action">
          <button class="cu-btn bg-gradual-orange shadow-blur round">搜索</button>
        </view> -->
      </view>
      <scroll-view v-if="hasData" scroll-y class="indexes" :scroll-into-view="listCurID" :style="[{height:'calc(100vh - '+ CustomBar + 'px - 50px)'}]" :scroll-with-animation="true" :enable-back-to-top="true">
        <view v-for="(item,index) in contactsData" :key="index" :id="item.letter">
          <view :class="item.letter" :id="item.letter" :data-index="item.letter">
            <view class="padding">{{item.letter}}</view>
            <view class="cu-list menu-avatar no-padding">
              <view class="cu-item" v-for="(subItem, sub) in item.contacts" :key="sub" @tap='onSelectClick(subItem)'>
                <view class="cu-avatar round lg">{{subItem.name.charAt(0)}}</view>
                <view class="content">
                  <view class="text-grey">{{subItem.name}}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view v-if="hasData" class="indexBar" :style="[{height:'calc(100vh - ' + CustomBar + 'px - 50px)'}]">
        <view class="indexBar-box" @touchstart="tStart" @touchend="tEnd" @touchmove.stop="tMove">
          <view class="indexBar-item" v-for="(item,index) in contactsData" :key="index" :id="index" @touchstart="getCur" @touchend="setCur"> {{item.letter}}</view>
        </view>
      </view>
      <!--选择显示-->
      <view v-show="!hidden" class="indexToast">
        {{listCur}}
      </view>
    </view>

    <text v-else class="no-contact">通讯录暂无联系人</text>
  </view>
</template>

<script>
import pinyin from '@/common/pinyin/pinyin3.js'

/**
 * 联系人列表数据例子
 * 
 * [
 *   {
 *     "letter":"A",
 *     "contacts":[{"name":"阿里巴巴钉钉客服","phone":"057128834033","phoneList":["057128834033"]}]
 *    }
 * ]
 * 
 */
export default {
  data() {
    return {
      contactsData: [],
      contactItems: [],
      isSearch: false,
      StatusBar: this.StatusBar,
      CustomBar: this.CustomBar,
      hidden: true,
      listCurID: '',
      listCur: '',
    };
  },
  computed: {
    hasData() {
      return this.contactsData.length
    }
  },
  onLoad() {
    // 初始化通讯录
    this.initContacts()
    // 从路由获取关系字段
    this.type = this.$Route.query.type
    this.typekey = this.$Route.query.typekey || ''
    if (this.hasData) { // 设置第一个字母为当前
      this.listCur = this.contactsData[0].letter
    }
  },
  onReady() {
    let that = this;
    uni.createSelectorQuery().select('.indexBar-box').boundingClientRect(function(res) {
      that.boxTop = res.top
    }).exec();
    uni.createSelectorQuery().select('.indexes').boundingClientRect(function(res) {
      that.barTop = res.top
    }).exec()
  },
  methods: {
    async initContacts() {
      const addressBookData = await this.$store.dispatch('getUserAddressBook')
      console.log('addressBookData', JSON.stringify(addressBookData))
      this.contactsData = pinyin.paixu(addressBookData)
      this.contactsData.sort((o1, o2) => {
        return o1.letter.charCodeAt(0) - o2.letter.charCodeAt(0)
      })
      this.contactItems = JSON.parse(JSON.stringify(this.contactsData))
    },
    /** 点击联系人 */
    onSelectClick(contact) {
      const { name, phoneList } = contact
      uni.showActionSheet({
        itemList: phoneList,
        success: (e) => {
          const phone = phoneList[e.tapIndex]
          console.log('点击联系人:', { name, phone })
          this.saveContact({ name, phone })
          this.$Router.back(1)
        }
      })
    },
    /** 保存联系人资料到vuex */
    saveContact(contact) {
      if (this.type === 'emergency') {
        let contactObj = {}
        contactObj[`${this.typekey}name`] = contact.name
        contactObj[`${this.typekey}phone`] = contact.phone
        this.$store.commit('SET_EMERGENCY_CONTACT', contactObj)
      } else {
        this.$store.commit('SET_SELECTED_CONTACT', contact)
      }
    },
    /** 搜索 */
    onSearchInput(e) {
      let searchVal = e.detail.value
      this.isSearch = true
      if (searchVal == '') {
        this.contactsData = JSON.parse(JSON.stringify(this.contactItems))
        this.isSearch = false
      } else {
        let showList = []
        let list = []
        list = JSON.parse(JSON.stringify(this.contactItems))
        list.forEach((item, index1) => {
          let contacts = []
          item.contacts.forEach((contact, index2) => {
            for (let i = 0; i < searchVal.length; i++) {
              if (contact.name.indexOf(searchVal[i]) != -1) {
                let contain = false
                contacts.find(function(val) {
                  if (val.phone == contact.phone) {
                    contain = true
                  }
                })
                if (!contain) {
                  contacts.push(contact);
                }
              }
            }
          })
          if (contacts.length > 0) {
            let target = {
              letter: item.letter,
              contacts: contacts
            }
            showList = showList.concat(target)
          }
        })
        setTimeout(() => {
          this.contactsData = JSON.parse(JSON.stringify(showList))
        }, 200)
      }
    },
    //获取文字信息
    getCur(e) {
      this.hidden = false;
      this.listCur = this.contactsData[e.target.id].letter;
    },
    setCur(e) {
      this.hidden = true;
      this.listCur = this.listCur
    },
    //滑动选择Item
    tMove(e) {
      let y = e.touches[0].clientY,
        offsettop = this.boxTop,
        that = this;
      //判断选择区域,只有在选择区才会生效
      if (y > offsettop) {
        let num = parseInt((y - offsettop) / 20);
        this.listCur = that.contactsData[num].letter
      };
    },

    //触发全部开始选择
    tStart() {
      this.hidden = false
    },

    //触发结束选择
    tEnd() {
      this.hidden = true;
      this.listCurID = this.listCur
    },
    indexSelect(e) {
      let that = this;
      let barHeight = this.barHeight;
      let list = this.list;
      let scrollY = Math.ceil(list.length * e.detail.y / barHeight);
      for (let i = 0; i < list.length; i++) {
        if (scrollY < i + 1) {
          that.listCur = list[i].name;
          that.movableY = i * 20
          return false
        }
      }
    }
  }
}
</script>

<style>
page {
  padding-top: 100rpx;
}

.indexes {
  position: relative;
}

.indexBar {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
  padding: 20rpx 20rpx 20rpx 60rpx;
  display: flex;
  align-items: center;
}

.indexBar .indexBar-box {
  width: 40rpx;
  height: auto;
  background: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
  border-radius: 10rpx;
}

.indexBar-item {
  flex: 1;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #888;
}

movable-view.indexBar-item {
  width: 40rpx;
  height: 40rpx;
  z-index: 9;
  position: relative;
}

movable-view.indexBar-item::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  top: 10rpx;
  height: 20rpx;
  width: 4rpx;
  background-color: #f37b1d;
}

.indexToast {
  position: fixed;
  top: 0;
  right: 80rpx;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  margin: auto;
  color: #fff;
  line-height: 100rpx;
  text-align: center;
  font-size: 48rpx;
}

.no-contact {
  position: fixed;
  width: 100%;
  margin-top: 300rpx;
  font-size: 35rpx;
  color: #666666;
  text-align: center;
}
</style>
